const fs = require("fs");
const CryptoJS = require("crypto-js");
/**
 * 读取路径信息
 * @param {string} filepath 路径
 */
function getStat(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err) {
        resolve(false);
      } else {
        resolve(stats);
      }
    });
  });
}

/**
 * 路径是否存在，不存在则创建
 * @param {string} dir 路径
 */
async function mkdir(dir) {
  let isExists = await getStat(dir);
  // console.log("------isExists-----", isExists);
  if (!isExists) {
    fs.mkdir(dir, { recursive: true }, (err) => {
      if (err) throw err;
    });
  }
}

/**
 * 路径是否存在，不存在则创建
 * @param {string} dir 路径
 */
async function mkdir2(dir) {
  let isExists = await getStat(dir);
  // console.log("------isExists-----", isExists);
  return new Promise((resolve, reject) => {
    if (!isExists) {
      fs.mkdir(dir, { recursive: true }, (err) => {
        if (err) throw reject(err);
        resolve("Created successfully");
      });
    } else {
      resolve(true);
    }
  });
}
/**
 * node v10.0.0 版本以后 路径是否存在，不存在则创建 递归版本
 * @param {string} dir 路径
 */
async function mkdir3(dir) {
  return new Promise((resolve, reject) => {
    fs.mkdir(dir, { recursive: true }, (err) => {
      if (err) throw reject(err);
      resolve("Created successfully");
    });
  });
}

function showByArrs(originData, arrs) {
  if (!originData || !arrs) {
    return;
  }

  let res = {};
  let rows = [];
  res.count = originData.count;
  if(originData.rows.length > 0){
    originData.rows.forEach(item=>{
      let obj = {};
      for (var prop in item) {
        if (arrs.includes(prop)) {
          obj[prop] = item[prop];
        }
      }
      rows.push(obj)
    })
  }
  res.rows = rows
  return res
}
function encrypt(word, keyStr) {
  keyStr = keyStr ? keyStr : "abcdefgabcdefg12";
  var key = CryptoJS.enc.Utf8.parse(keyStr); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
}
function decrypt(word, keyStr) {
  keyStr = keyStr ? keyStr : "abcdefgabcdefg12";
  var key = CryptoJS.enc.Utf8.parse(keyStr); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(word, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

module.exports = {
  mkdir,
  mkdir2,
  getStat,
  mkdir3,
  showByArrs,
  encrypt,
  decrypt
};
